<template>
	<view class="the-page">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<uni-forms :model="userForm" ref="form1">
			<uni-forms-item label="用户" prop="name" borderBottom required>
				<uni-easyinput type="text" v-model="userForm.name" border="none" placeholder="请输入用户" clearable></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="密码" prop="password" borderBottom required>
				<uni-easyinput type="password" v-model="userForm.password" border="none" placeholder="请输入密码"
					clearable></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="确认" prop="password2" borderBottom required>
				<uni-easyinput type="password" v-model="userForm.password2" border="none" placeholder="请确认密码"
					clearable></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="邮箱" prop="email" borderBottom required>
				<uni-easyinput type="text" v-model="userForm.email" border="none" placeholder="请输入邮箱" clearable></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="电话" prop="phone" borderBottom required>
				<uni-easyinput type="text" v-model="userForm.phone" border="none" placeholder="请输入电话" clearable></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="性别" prop="gender" borderBottom>
				<u-radio-group v-model="userForm.gender" placement="row">
					<u-radio :name="1">男</u-radio>
					<u-radio :name="0" style="margin-left: 10px;">女</u-radio>
				</u-radio-group>
			</uni-forms-item>
			<uni-forms-item label="昵称" borderBottom><uni-easyinput type="text" placeholder="请输入昵称" v-model="userForm.nickName"
					border="none"></uni-easyinput></uni-forms-item>
			<uni-forms-item label="头像">
				<uni-file-picker :value="fileList" limit="1" :del-icon="true" disable-preview file-mediatype="image"
					@select="onSelect">选择</uni-file-picker>
			</uni-forms-item>
		</uni-forms>
		<button type="primary" @click="onSubmit">提交</button>
		<button type="error" style="margin-top: 10px" @click="onReset">重置</button>

		<div>注册成功后的用户可用于登录</div>
	</view>
</template>

<script>
	import * as UserAPI from '@/api/user.js';
	import { setStorageUser } from '@/utils/storage.js';
	import * as FileAPI from "@/api/file.js";
	export default {
		data() {
			return {
				userForm: {
					//表单中的字段名与数据库中用户表的字段名要求一致
					name: '',
					password: '',
					password2: '',
					email: 'wattt@163.com',
					phone: '15958880000',
					gender: 1,
					avatar: '',
					nickName: ''
				},
				fileList: [],

				rules: {
					name: {
						type: 'string',
						required: true,
						pattern: /^[a-z0-9]{3,12}$/i,
						message: '3-12字符',
						trigger: ['blur', 'change']
					},
					password: {
						type: 'string',
						required: true,
						pattern: /^[a-z0-9]{3,12}$/i,
						message: '3-12字符',
						trigger: ['blur', 'change']
					},
					password2: {
						type: 'string',
						required: true,
						pattern: /^[a-z0-9]{3,12}$/i,
						message: '3-12字符',
						trigger: ['blur', 'change']
					},
					email: {
						type: 'email',
						required: true,
						message: '无效的邮箱地址',
						trigger: ['blur', 'change']
					},
					phone: {
						type: 'string',
						required: true,
						pattern: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/,
						message: '无效的手机号码',
						trigger: ['blur', 'change']
					}
				}
			};
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules);
		},

		methods: {
			onSelect(params) {
				console.log("onSelect", params);
				// this.uploadFile(params.tempFiles[0])
				FileAPI.uploadFile(params.tempFiles[0].file).then(result => {
					console.log(result)
					// 重新生成显示的图片url
					this.fileList = [];
					let url = result.url;
					this.fileList.push({
						url: url
					})
					//设置用户表中的字段值
					this.userForm.avatar = url;

				})
			},
			onSuccess(params) {
				console.log("onSuccess", params);
			},
			onProgress(params) {
				console.log("onProgress", params);
			},
			onFail(params) {
				console.log("onFail", params);
			},
			// 删除图片
			onDelete(params) {
				console.log("onDelete", params);

				// 删除云端存储的文件
				let pathes = [];
				this.fileList.forEach(item => {
					pathes.push(item.url)
				})
				// FileAPI.deleteFile(pathes).then(result => {
				// 	console.log(result.message)
				// }).catch(error => {
				// 	console.log(error)
				// })

				this.fileList = [];
				//设置用户表中的字段值
				this.userForm.avatar = "";
			},

			// 上传图片
			uploadFile(file) {
				console.log(file)

				file.status = 'uploading';
				file.message = '上传中...';
				// console.log(file)
				let formData = new FormData();
				formData.append("file", file.file);

				FileAPI.uploadFile(file.file).then(result => {
					console.log(result)
					file.status = '';
					file.message = '';
					//重新生成显示的图片url
					// this.fileList = [];
					// let url = result.data.url;
					// this.fileList.push({
					// 	url: this.$fullUrl(url)
					// })
					// //设置用户表中的字段值
					// this.userForm.avatar = url;
				});
			},

			//处理提交保存
			onSubmit() {
				if (this.userForm.password != this.userForm.password2) {
					uni.showToast({
						title: "密码两次输入不一致！"
					});
					return;
				}
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1
					.validate()
					.then(valid => {
						if (valid) {
							//注意传递过去的参数user的属性名
							let user = this.userForm;
							delete user.password2; //删除该临时的字段
							UserAPI.register(user).then(result => {
								//保存用户信息（id,name） 注意：还是处于未登录
								setStorageUser(result.data.user);
								uni.reLaunch({
									url: "/pages/user/user",
								})
							});
						}
					})
					.catch(() => {
						uni.showToast({
							title: "校验失败！"
						});
					});
			},

			onReset() {
				this.$refs.form1.resetFields();
				setTimeout(() => {
					this.$refs.form1.clearValidate();
				}, 10);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.the-page {
		padding: 20px;
	}

	uni-button {
		margin: 10px 0;
	}
</style>